#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <pthread.h>

#define N 10000000
#define NTHREAD 8

int pontos_in[NTHREAD];
int pontos_total[NTHREAD];

const unsigned int num = 1664525, num2 = 1013904223;

unsigned int rand_function(unsigned int x)
{
        return x*num+num2;
}

void *calcula(void *parametro){

    double x,y;
    int num = *((int *)parametro);
    pontos_in[num] = pontos_total[num] = 0;

    unsigned int aux = time(NULL);

    while(pontos_total[num] < N/NTHREAD){

    aux = rand_function(aux);
    x = (double) aux/UINT_MAX;
    aux = rand_function(aux);
    y = (double) aux/UINT_MAX;

    //printf("%lf   %lf\n",x,y);


    if((x*x) + (y*y) <= 1){
        pontos_in[num]++;
        }

    pontos_total[num]++;

    }

    pthread_exit(0);
}

void monteCarloPar(void){
    double pi;
    int total_pontos_in = 0, total_pontos = 0,i;
    pthread_t thread[NTHREAD];
    srand(time(NULL));

    // Para todas as threads
	for (i = 0; i< NTHREAD ; i++){
	// cria a i-esima thread
	pthread_create (&thread[i], NULL, calcula, &i);
       }

	// Para cada thread
	for (i = 0; i< NTHREAD ; i++){
	// espera que as threads terminem
	pthread_join (thread[i], NULL);
       }

      for (i = 0; i< NTHREAD ; i++){
          total_pontos += pontos_total[i];
          total_pontos_in += pontos_in[i];
       }

    pi = 4.0*((((double)total_pontos_in))/((double)total_pontos));

    printf("%lf",pi);
}
